<template>
  <div class="row">
    <h2 v-if="firstView">请输入关键字收索Github用户</h2>
    <h2 v-else-if="loading">正在请求中...</h2>
    <h2 :style="{color:'red'}" v-else-if="errorMsg">{{ errorMsg }}</h2>
    <div v-else class="card" v-for="user in users" :key="user.userName">
      <a :href="user.url" target="_blank">
        <img :src="user.avatar_url" style="width: 100px" />
      </a>
      <p class="card-text">reactjs</p>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "Main",
  data() {
    return {
      firstView: true,
      loading: false,
      users: [],
      errorMsg: "",
    };
  },
  mounted() {
    //   事件总线来实现任意两个组件之间的通信
    this.$bus.$on("search", this.search);
  },
  methods: {
    search(searchName) {
      //   准备发送请求
      this.firstView = false;
      this.loading = true;
      axios
        .get(`https://api.github.com/search/users2?q=${searchName}`)
        .then((response) => {
          // 请求到数据不需要在显示等待界面
          this.loading = false;
          const data = response.data;
          const users = data.items.map((item) => ({
            userName: item.login,
            avater_url: item.avatar_url,
            url: item.html_url,
          }));
          this.users = users;
        })
        .catch((error) => {
          this.loading = false;
          this.errorMsg = error.message;
        });
    },
  },
};
</script>

<style scoped>
.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
